package com.jmpt.fangbohui.ui.personalcenter;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.adapter.HouseSeleteMoreAdapter;
import com.jmpt.fangbohui.adapter.OrderListAdapter;
import com.jmpt.fangbohui.adapter.OrderSelectStateAdapter;
import com.jmpt.fangbohui.adapter.OrderSelectTypeAdapter;
import com.jmpt.fangbohui.bean.BrokerOrderBean;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.helper.CommonHelper;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.SearchActivity;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.jmpt.fangbohui.utils.UIUtils;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

public class BrokerOrderActivity extends BaseHeadActivity implements
		OnClickListener {

	private static final int SEARCH_REQUEST_CODE = 111;
	private static final String TAG = "BrokerOrderActivity.java";
	private Button btn_typeSelete;
	private Button btn_stateSelete;
	private PullToRefreshListView plv_orderList;
	private RelativeLayout mLoading;
	private ViewStub vs_seleteArea;
	private boolean isFirstLoad;
	private boolean isNoMore;
	private String currSearchKey;
	private OrderListAdapter mOrderListAdapter;
	private OrderSelectTypeAdapter mOrderSelectTypeAdapter;
	private OrderSelectStateAdapter mOrderSelectStateAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_list);
		// 设置标题
		showTitle("订单管理");
		// 设置返回键
		showBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		showRightImageButton(R.drawable.ic_home_search,
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						 Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
						 intent.putExtra(SearchActivity.CURR_KEY, currSearchKey);
						 startActivityForResult(intent,SEARCH_REQUEST_CODE);
					}
				});

		assignViews();
		initView();
	}

	private void initView() {
//		addMenuItem(R.drawable.btn_main_home,"主页");
//		addMenuItem(R.drawable.btn_main_home,"搜索1");
//		addMenuItem(R.drawable.btn_main_home,"搜索2");
		mOrderListAdapter = new OrderListAdapter(this);
		plv_orderList.setAdapter(mOrderListAdapter);
		plv_orderList.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
		plv_orderList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> adapterView,
							View view, int i, long l) {
					}
				});
		
		plv_orderList
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						fistLoad();
					}
					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						if(isNoMore){
							ToastHelper.ShowToast("没有更多数据了", getApplicationContext());
							plv_orderList.onRefreshComplete();
							return;
						}
						// 加载更多
						loadMore();
					}
				});

		plv_orderList.setOnScrollListener(new PauseOnScrollListener(ImageLoaderHelper.getImageLoader(), true, true));  
		
		
		mOrderSelectTypeAdapter = new OrderSelectTypeAdapter(this);
		mOrderSelectTypeAdapter.data = CommonHelper.getOrderTypeBeans();
		
		mOrderSelectStateAdapter = new OrderSelectStateAdapter(this);
		mOrderSelectStateAdapter.data = CommonHelper.getOrderStateBeans();
		
		initSeleteView();

		btn_typeSelete.setOnClickListener(this);
		btn_stateSelete.setOnClickListener(this);

		fistLoad();

	}

	private void fistLoad() {
		isNoMore = false;
		load(true);
	}

	private void assignViews() {

		btn_typeSelete = (Button) findViewById(R.id.btn_order_list_type);
		btn_stateSelete = (Button) findViewById(R.id.btn_order_list_state);

		plv_orderList = (PullToRefreshListView) findViewById(R.id.plv_order_list_content);
		mLoading = (RelativeLayout) findViewById(R.id.rel_order_list_loading);
		vs_seleteArea = (ViewStub) findViewById(R.id.vs_order_list_seleteArea);
		// 查找筛选区域视图
		v_seleteArea = vs_seleteArea.inflate();
		v_seleteArea.setVisibility(View.INVISIBLE);
		assignSeleteViews(v_seleteArea);
	}

	private ImageView iv_seleteArea;
	private ListView lv_seleteArea_left;
	private ListView lv_seleteArea_right;
	private View v_seleteArea;
	protected int mCurrenTypeIndex;
	protected int mCurrenStateIndex;
	protected int mCurrenOrderIndex;
	
//	private int mCurrenMoreLeftIndex;
	//一页显示10条数据
	private int limit = Constants.limit.NEW_HOUSE_PAGE_LIMIT;

	private void assignSeleteViews(View view) {
		iv_seleteArea = (ImageView) view
				.findViewById(R.id.iv_house_group_select_background);
		lv_seleteArea_left = (ListView) view
				.findViewById(R.id.lv_house_group_select_left);
		lv_seleteArea_right = (ListView) view
				.findViewById(R.id.lv_house_group_select_right);

	}

	public void initSeleteView() {
		lv_seleteArea_left
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						if (lv_seleteArea_left.getAdapter() instanceof OrderSelectTypeAdapter) {

							mCurrenTypeIndex = position;
							for (int i = 0; i < mOrderSelectTypeAdapter.data
									.size(); i++) {
								mOrderSelectTypeAdapter.data.get(i).isSelete = false;
							}
							mOrderSelectTypeAdapter.data.get(position).isSelete = true;
							mOrderSelectTypeAdapter.notifyDataSetChanged();
							hideSeleteArea();
							fistLoad();
							refreshTypeButtonName();
						}
						if (lv_seleteArea_left.getAdapter() instanceof OrderSelectStateAdapter) {
							mCurrenStateIndex = position;
							for (int i = 0; i < mOrderSelectStateAdapter.data.size(); i++) {
								mOrderSelectStateAdapter.data.get(i).isSelete = false;
							}
							mOrderSelectStateAdapter.data.get(position).isSelete = true;
							mOrderSelectStateAdapter.notifyDataSetChanged();
							hideSeleteArea();
							fistLoad();
							refreshStateButtonName();
						}
					}
				});

		iv_seleteArea.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				hideSeleteArea();
			}
		});
	}

	protected void refreshStateButtonName() {
		if(mCurrenStateIndex == 0){
			btn_stateSelete.setText("交易状态");
		}else{
			btn_stateSelete
			.setText(mOrderSelectStateAdapter.data.get(mCurrenStateIndex).Order_Status_name);
		}
	}

	protected void refreshTypeButtonName() {
		if(mCurrenTypeIndex == 0){
			btn_typeSelete.setText("房源类型");
		}else{
			btn_typeSelete.setText(mOrderSelectTypeAdapter.data
					.get(mCurrenTypeIndex).H_SaleOrRent_name);
		}
	}

	/**
	 * 隐藏条件筛选区
	 */
	private void hideSeleteArea() {
		ObjectAnimator animator = ObjectAnimator.ofFloat(lv_seleteArea_left,
				"translationY", 0, -lv_seleteArea_left.getHeight());
		animator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animation) {

			}

			@Override
			public void onAnimationEnd(Animator animation) {
				v_seleteArea.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onAnimationCancel(Animator animation) {

			}

			@Override
			public void onAnimationRepeat(Animator animation) {

			}
		});

		ObjectAnimator translationRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "translationY", 0,-lv_seleteArea_right.getHeight());
		ObjectAnimator alphaArea = ObjectAnimator.ofFloat(iv_seleteArea, "alpha", 1f, 0f);
		ObjectAnimator alphaRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "alpha", 1f, 0f);
		AnimatorSet set = new AnimatorSet();
		set.playTogether(animator,translationRight,alphaArea,alphaRight);
		set.start();
	}
	
	 private void showSeleteArea() {

	        ViewTreeObserver vto2 = lv_seleteArea_left.getViewTreeObserver();

	        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
	            @Override
	            public void onGlobalLayout() {
	            	lv_seleteArea_left.getViewTreeObserver().removeGlobalOnLayoutListener(this);
	                int height = lv_seleteArea_left.getHeight();
	                int width = lv_seleteArea_left.getWidth();
	                DebugLog.e("height: " + height);
	                DebugLog.e("width: " + width);
	                if (lv_seleteArea_left.getAdapter() instanceof HouseSeleteMoreAdapter) {
//	                    ViewGroup.LayoutParams layoutParams = lv_seleteArea_right.getLayoutParams();
//	                    layoutParams.height = height;
//	                    lv_seleteArea_right.setLayoutParams(layoutParams);
	                    lv_seleteArea_right.setVisibility(View.VISIBLE);
	                } else {
	                	lv_seleteArea_right.setVisibility(View.GONE);
	                }
	                
	                ObjectAnimator animatorLeft = ObjectAnimator.ofFloat(lv_seleteArea_left, "translationY", -lv_seleteArea_left.getHeight(), 0);

	                animatorLeft.addListener(new Animator.AnimatorListener() {
	                    @Override
	                    public void onAnimationStart(Animator animation) {

	                        v_seleteArea.setVisibility(View.VISIBLE);

	                    }

	                    @Override
	                    public void onAnimationEnd(Animator animation) {

	                    }

	                    @Override
	                    public void onAnimationCancel(Animator animation) {

	                    }

	                    @Override
	                    public void onAnimationRepeat(Animator animation) {

	                    }
	                });
	                ObjectAnimator alphaArea = ObjectAnimator.ofFloat(iv_seleteArea, "alpha", 0f, 1f);
	                ObjectAnimator translationRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "translationY", -lv_seleteArea_right.getHeight(), 0);
	                ObjectAnimator alphaRight = ObjectAnimator.ofFloat(lv_seleteArea_right, "alpha", 0f, 1f);
	                AnimatorSet set = new AnimatorSet();
	                set.playTogether(animatorLeft,translationRight,alphaArea,alphaRight);
	                set.start();
	            }
	        });
	    }

	private void load(boolean isFrist) {
		isFirstLoad = isFrist;
		
		int typeId = 0;
		int stateId = 0;
		if (mCurrenTypeIndex > 0) {
			typeId = mOrderSelectTypeAdapter.data.get(mCurrenTypeIndex).H_SaleOrRent_id;
		}
		
		if (mCurrenStateIndex > 0) {
			stateId = mOrderSelectStateAdapter.data.get(mCurrenStateIndex).Order_Status_id;
		}
		
//		int page;
//		//是否是第一次加载 | 或者更改筛选条件后重新加载
//		if (isFirstLoad) {
//			page = 1;
//		} else {
//			//追加数据
//			page = mOrderListAdapter.getCount() / limit  + 1;
//		}
		
		//TODO
		LoginBean loginBean = new LoginSQLiteOperator(this).query();
		if(loginBean == null){
			//跳转到登录界面
			Intent loginIntent = new Intent(mContext,LoginActivity.class);
			mContext.startActivity(loginIntent);
			finish();
			return;
		}
		
		addRequestHandle(ApiRequest.getBrokerOrderData(loginBean, currSearchKey, 
				new HttpOrderListHandler(this,false)));
		
		//模拟假数据
		/*Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				paseOrderJson("[{\"H_SaleOrRent\": [{\"H_SaleOrRent_id\": \"1\",\"H_SaleOrRent_name\": \"售房\"},{\"H_SaleOrRent_id\": \"2\",\"H_SaleOrRent_name\": \"租房\"}],\"Order_Status\": [{ \"Order_Status_id\": \"1\",\"Order_Status_name\": \"等待付款\"}],\"data\": [{\"AddDate\": \"2015-05-21 16:14:13\",\"BuyerName\": \"温景庭\", \"BuyerTel\": \"13751869490\",\"H_Hall\": \"2\",\"H_MJ\": \"120\",\"H_Room\": \"3\",\"H_SalePrice\": \"122\",\"H_SaleUnitPrice\": \"10000\",\"H_Title\": \"houseForJimi\",\"H_payment\": \"0.02\",\"OrderNum\": \"00020092305\",\"Order_Status\": \"已取消\",\"SaleUnitPrice_type\": \"元/平米\",\"Saleprice_type\": \"万\"},{\"AddDate\": \"2015-05-21 16:14:13\",\"BuyerName\": \"温景庭\", \"BuyerTel\": \"13751869490\",\"H_Hall\": \"2\",\"H_MJ\": \"120\",\"H_Room\": \"3\",\"H_SalePrice\": \"122\",\"H_SaleUnitPrice\": \"10000\",\"H_Title\": \"houseForJimi\",\"H_payment\": \"0.02\",\"OrderNum\": \"00020092305\",\"Order_Status\": \"已取消\",\"SaleUnitPrice_type\": \"元/平米\",\"Saleprice_type\": \"万\"}]}]");
			}
		}, 1000);*/
		
		DebugLog.i("typeId:" + typeId);
		DebugLog.i("stateId:" + stateId);
	}

	private void loadMore() {
		load(false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_order_list_type:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof OrderSelectTypeAdapter) {
					hideSeleteArea();
				} else {                 
					lv_seleteArea_left.setAdapter(mOrderSelectTypeAdapter);
					mOrderSelectTypeAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.GONE);
				}
			} else {
				lv_seleteArea_left.setAdapter(mOrderSelectTypeAdapter);
				mOrderSelectTypeAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.GONE);
				showSeleteArea();
			}

			break;
		case R.id.btn_order_list_state:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof OrderSelectStateAdapter) {
					hideSeleteArea();
				} else {
					lv_seleteArea_left.setAdapter(mOrderSelectStateAdapter);
					mOrderSelectStateAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.GONE);
				}
			} else {
				lv_seleteArea_left.setAdapter(mOrderSelectStateAdapter);
				mOrderSelectStateAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.GONE);
				showSeleteArea();
			}

			break;

		/*case R.id.btn_newhouse_list_moreSelete:
			if (v_seleteArea.getVisibility() == View.VISIBLE) {
				if (lv_seleteArea_left.getAdapter() instanceof HouseSeleteMoreAdapter) {
					hideSeleteArea();
				} else {
					lv_seleteArea_left.setAdapter(mSelectMoreLeftAdapter);
					mSelectMoreLeftAdapter.notifyDataSetChanged();
					lv_seleteArea_right.setVisibility(View.VISIBLE);
					lv_seleteArea_right.setAdapter(mSeleteMoreRightAdapter);
					mSeleteMoreRightAdapter.data = mSelectMoreLeftAdapter.data.get(mCurrenMoreLeftIndex);
					mSeleteMoreRightAdapter.notifyDataSetChanged();
				}
			} else {
				lv_seleteArea_left.setAdapter(mSelectMoreLeftAdapter);
				mSelectMoreLeftAdapter.notifyDataSetChanged();
				lv_seleteArea_right.setVisibility(View.VISIBLE);
				lv_seleteArea_right.setAdapter(mSeleteMoreRightAdapter);
				mSeleteMoreRightAdapter.data = mSelectMoreLeftAdapter.data.get(mCurrenMoreLeftIndex);
				mSeleteMoreRightAdapter.notifyDataSetChanged();

				showSeleteArea();
			}
			break;*/
		}
	}
	
	
	class HttpOrderListHandler extends JsonHttpHandler {

		public HttpOrderListHandler(Context context, boolean fromCache) {
			super(context, fromCache);
		}

		public HttpOrderListHandler(Context context) {
			super(context);
		}

		@Override
		public void onStart() {
			if (isFirstLoad) {
				//mLoading.setVisibility(View.VISIBLE);
				setShowProgressDialog("正在加载中...");
//				plv_orderList.setRefreshing(true);
			} else {
				//增加加载更多
				plv_orderList.setRefreshing(true);
			}
			super.onStart();
		}

		@Override
		public void onFinish() {
			super.onFinish();
			plv_orderList.onRefreshComplete();
		}
		
		@Override
		public void onCacheDo(String cache) {
			paseOrderJson(cache);
		}

		@Override
		public void onDo(String response) {
			super.onDo(response);
			paseOrderJson(response);
		}
		
	}
	
	public void paseOrderJson(String response) {
		plv_orderList.onRefreshComplete();
		try {
			
			JSONArray jsonArray = new JSONArray(response);
			JSONArray orderJsonArr = jsonArray.getJSONObject(0).getJSONArray("data");
			
			
			List<BrokerOrderBean> entities = new Gson().fromJson(orderJsonArr.toString(),
					new TypeToken<List<BrokerOrderBean>>() {}.getType());
			//TODO
			
			
//			List<NewHouseBean> entities = new Gson().fromJson(response,
//					new TypeToken<List<NewHouseBean>>() {}.getType());
			if (isFirstLoad) {
				mOrderListAdapter.orderList.clear();
			}
//			//获取回来的数据小于每页的数据  则说明没有更多数据了
//			if (entities == null || entities.size() < limit) {
//				//只能刷新 ， 不可加载更多
				plv_orderList.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
//				isNoMore = true; //无更多数据了
//			}else{
//				plv_orderList.setMode(PullToRefreshBase.Mode.BOTH);
//				DebugLog.i("entities.size():" + entities.size());
//			}
//			
			if(entities != null ){
				mOrderListAdapter.orderList.addAll(entities);
			}
//			
			mOrderListAdapter.notifyDataSetChanged();
//			
			if(isFirstLoad){
				plv_orderList.getRefreshableView().setSelection(0);
			}
//			
//			DebugLog.i("mAdapter.getCount():" + mHouseListAdapter.getCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == SEARCH_REQUEST_CODE && resultCode == RESULT_OK && data != null){
			String stringExtra = data.getStringExtra("search_key");
			currSearchKey = stringExtra;
			
			if(!TextUtils.isEmpty(currSearchKey)){
				showTitle("搜索 \"" + currSearchKey + "\"");
			}else{
				showTitle("订单管理");
			}
			
			fistLoad();
			
			return;
		}
	}
	
	@Override
	public void onBackPressed() {
		if(v_seleteArea.getVisibility() == View.VISIBLE){
			hideSeleteArea();
			return;
		}
		super.onBackPressed();
	}

}
